"""Copyright - ServePath Inc.
"""
import md5
import time
import urllib
import simplejson as json

class GoGridClient:
  """sample gogrid api client"""
  default_params = {'format':'json', 'v':'1.0'}
  server = 'https://api.gogrid.com/api'
  api_key = 'YOUR API KEY'
  secret = 'YOUR SHARED SECRET'
  
  def __init__(self,server='',key='',secret=''):
    if server != "":
        self.server = server
    if key != "":
        self.api_key = key
    if secret != "":
        self.secret = secret
    self.default_params['api_key'] = self.api_key
    self.default_params['secret'] = self.secret
  
  def getRequestURL(self,method,params={}):
    """ constructs a call url from a given method with params """
    requestURL = self.server+'/'+method+'?'
    call_params = self.default_params.copy()
    call_params.update(params)
    call_params['sig'] = self.getSignature(call_params['api_key'],call_params['secret'])
    del call_params['secret']
    requestURL += urllib.urlencode(call_params)
    return requestURL
  
  def getSignature(self,key,secret):
    """ create sig from md5 of key + secret + time """
    m = md5.new(key+secret+str(int(time.time())))
    return m.hexdigest()
        
  def sendAPIRequest(self,method,params={}):
    """ send a request and return response """
    url = self.getRequestURL(method,params)
    f = urllib.urlopen(url)
    return f.read()
    
  def request(self,method,params={}):
    """ send a request and return response """
    return json.loads(self.sendAPIRequest(method,params))
